import acm.graphics.GOval;
import acm.program.GraphicsProgram;

import java.awt.*;
import java.util.ArrayList;
import java.util.Random;

public class ThreeBodyProgram extends GraphicsProgram {
    public static final double TIME_STEP = 0.01;
    public static final int APPLICATION_WIDTH = 400;
    public static final int APPLICATION_HEIGHT = 300;

    // 程序会从这里开始运行
    @Override
    public void run() {
        var galaxy = new Galaxy();
        ArrayList<Body> bodies = CreateStars(3);
        galaxy.setBodies(bodies);

        while (true) {
            clear();
            galaxy.increaseTime(TIME_STEP);
            for (Body body : bodies) {
                drawNormalize(body);
            }
            pause(2);
        }
    }

    void drawNormalize(Body body) {
        var x = body.loc.x + 200;
        var y = body.loc.y + 150;
        System.out.println(body.name);
        System.out.println("loc" + body.loc);
        System.out.println("velocity" + body.velocity);
        var oval = new GOval(x, y, 10, 10);
        oval.setFilled(true);
        add(oval);
    }

    //通过精密的数学计算，可以让任意多的天体组织
    public static ArrayList<Body> CreateStars(int N) {
        ArrayList<Body> bodies = new ArrayList<>();
        for (var i = 0; i < N; ++i) {
            double angle = 1.0f * i / N * Math.PI * 2;
            double R = 45;
            double M = 10000 * 2 / (N * Math.sqrt(N) * Math.log(N));
            double v = 5;
            double px = R * Math.sin(angle);
            double py = R * -Math.cos(angle);
            double vx = v * Math.cos(angle);
            double vy = v * Math.sin(angle);
            Body body = new Body(px, py, vx, vy, M);
            body.name= getRandomString(5);
            System.out.println(body);
            bodies.add(body);
        }
        return bodies;
    }

    //length用户要求产生字符串的长度
    public static String getRandomString(int length){
        String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random=new Random();
        StringBuffer sb=new StringBuffer();
        for(int i=0;i<length;i++){
            int number=random.nextInt(62);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }

}